package tech.wetech.admin3.sys.service;

import cn.hutool.core.util.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import tech.wetech.admin3.sys.model.AooEmailCode;
import tech.wetech.admin3.sys.repository.EmailRepository;

import java.time.Instant;

@Service
public class EmailService {
  @Autowired
  private EmailRepository emailRepository;
  // mail依赖发送邮件的接口
  @Autowired
  private JavaMailSender mailSender;

  // 获取发件人邮箱
  @Value("${spring.mail.username}")
  private String sender;

  public String getCode(String email) {
    SimpleMailMessage message = new SimpleMailMessage();
    message.setFrom('<' + sender + '>');
    message.setTo(email);

    String code = RandomUtil.randomNumbers(6);

    String text = "【验证码】您的验证码为：" + code + "\n\n\n";
    message.setText(text);

    mailSender.send(message);

    AooEmailCode emailCode = emailRepository.findByEmail(email).orElseGet(() -> new AooEmailCode());
    emailCode.setCode(code);
    emailCode.setEmail(email);
    emailCode.setExpirationTime(Instant.now().plusSeconds(300).toEpochMilli());
    emailRepository.save(emailCode);

    return code;
  }

  public boolean verifyCode(String email, String code){
    AooEmailCode emailCode = emailRepository.findByEmail(email).orElse(null);
    return emailCode != null
      && emailCode.getCode().equals(code)
      && emailCode.getExpirationTime() >= Instant.now().toEpochMilli();  // 验证码校验
  }

  public void deleteCode(String email){
    AooEmailCode emailCode = emailRepository.findByEmail(email).orElse(null);
    emailRepository.delete(emailCode);
  }
}
